package cn.izeno.wx

import org.ehcache.CacheManager
import org.ehcache.config.builders.CacheConfigurationBuilder
import org.ehcache.config.builders.CacheManagerBuilder
import org.ehcache.config.builders.ResourcePoolsBuilder
import org.ehcache.config.units.MemoryUnit
import java.io.File
import java.io.Serializable

object Cache {
  private val cacheManager: CacheManager

  init {
    // 获取当前程序所在路径
    val path = System.getProperty("user.dir")
    val cacheConfig = CacheConfigurationBuilder.newCacheConfigurationBuilder(
        String::class.java, Serializable::class.java,
        // 内存缓存 10 实例, 缓存 1M
        ResourcePoolsBuilder.heap(10).disk(1, MemoryUnit.MB, true)
    )
    cacheManager = CacheManagerBuilder.newCacheManagerBuilder()
        .with(CacheManagerBuilder.persistence("$path${File.separatorChar}/ehcache"))
        .withCache("wx", cacheConfig)
        .build()
  }

  operator fun get(k: String): Serializable? {
    var result: Serializable? = null
    synchronized(cacheManager) {
      cacheManager.init()
      val cache = cacheManager.getCache("wx", String::class.java, Serializable::class.java)
      result = cache[k]
      cacheManager.close()
    }

    return result

  }

  operator fun set(k: String, v: Serializable?) {
    synchronized(cacheManager) {
      cacheManager.init()
      val cache = cacheManager.getCache("wx", String::class.java, Serializable::class.java)
      cache[k] = v
      cacheManager.close()
    }
  }
}
